package com.zz.utils;


/**
 *
 * @Introductions
 * 
 *                【系统工具类】
 * 
 * @company 青岛泽印网络科技有限公司 http://www.qdzeyin.com
 * 
 * @copyright 青岛泽印网络有限公司，版权所有，保留所有权利
 * 
 * @author Guoqi
 * 
 * @date 2016年9月9日 上午10:07:30
 * 
 * @versions 1.0
 * 
 */
import java.io.File;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import com.zz.repository.Userrole.Userrole;
import com.zz.repository.user.User;

public class Util {

  /**
   * 获得对象的整数类型
   * 
   * @param obj
   *          任意对象
   * @return 异常值为：0
   */

  public static int getInt(Object obj) {
    if (null == obj) {
      return 0;
    }
    int result = 0;
    try {
      result = Integer.parseInt(obj.toString());
    } catch (NumberFormatException e) {
      return 0;
    }
    return result;
  }

  public static double getDouble(Object obj) {
    if (null == obj) {
      return 0;
    }
    double result = 0;
    try {
      result = Double.parseDouble(obj.toString());
    } catch (NumberFormatException e) {
      return 0;
    }
    return Double.parseDouble(new DecimalFormat("#.00").format(result));
  }

  /**
   * 获得对象的Long类型
   * 
   * @param obj
   *          任意对象
   * @return 异常值为：0
   */

  public static long getLong(Object obj) {
    if (isEmpty(obj)) {
      return 0l;
    }
    long result = 0l;
    try {
      result = Long.parseLong(obj.toString().trim());
    } catch (NumberFormatException e) {
      return 0l;
    }
    return result;
  }

  /**
   * 获得对象的float类型
   * 
   * @param obj
   * @return
   */

  public static float getFloat(Object obj) {
    if (null == obj) {
      return 0l;
    }
    float result = 0l;
    try {
      result = Float.parseFloat(obj.toString());
    } catch (NumberFormatException e) {
      return 0;
    }
    return result;
  }

  /**
   * 获得对象的short类型
   * 
   * @param obj
   * @return
   */

  public static short getShort(Object obj) {
    if (null == obj) {
      return 0;
    }
    short result = 0;
    try {
      result = Short.parseShort(obj.toString());
    } catch (NumberFormatException e) {
      return 0;
    }
    return result;
  }

  /**
   * 获得对象的字符串类型
   * 
   * @param obj
   *          任意对象
   * @return 该对象的字符串
   */

  public static String getString(Object obj) {
    if (null == obj) {
      return "";
    }
    return obj.toString();
  }

  /**
   * 判断对象是否为空(null或空串)
   * 
   * @param obj
   *          任意对象
   * @return 布尔值
   */

  public static boolean isEmpty(Object obj) {
    if (null == obj || "".equals(obj)) {
      return true;
    }
    return false;
  }

  public static boolean isEmpty(List<?> list) {
    if (null == list || list.isEmpty()) {
      return true;
    }
    return false;
  }

  public static boolean isEmpty(Object obj[]) {
    if (null == obj || obj.length == 0) {
      return true;
    }
    return false;
  }

  /**
   * 获得IP
   * 
   * @param request
   * @return
   */
  public static String getIP(HttpServletRequest request) {
    String ip = request.getHeader("x-forwarded-for");
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getRemoteAddr();
    }
    return ip;
  }

  /**
   * 模糊查询使用,拆分字符串拼入"%"
   * 
   * @param text
   * @return
   */
  public static String convertToLikeSearchText(String text) {
    char cs[] = text.toCharArray();
    StringBuffer result = new StringBuffer("%");
    for (char c : cs) {
      result.append(c).append("%");
    }
    return result.toString();
  }

  /**
   * 模糊查询使用,拆分字符串拼入查询语句 更详细匹配
   * 
   * @param text
   *          查询关键字
   * @param field
   *          字段
   * @return
   */
  public static String convertToLikeSearchText(String text, String field) {
    char cs[] = text.toCharArray();
    StringBuffer result = new StringBuffer();
    result.append(" ( ");
    for (int i = 0; i < cs.length; i++) {
      String c = String.valueOf(cs[i]);
      if (i == 0) {
        result.append(" lower(" + field + ") like '%" + c.toLowerCase() + "%' ");
      } else {
        result.append(" and lower(" + field + ") like '%" + c.toLowerCase() + "%' ");
      }
    }
    result.append(" ) ");
    return result.toString();
  }

  /**
   * 获取文件扩展名
   * 
   * @param file
   * @return
   */
  public static String getFileExtName(File file) {
    StringBuilder sb = new StringBuilder(file.getName()).reverse();
    String ext = new StringBuilder(sb.substring(0, sb.indexOf("."))).reverse().toString();
    return ext;
  }

  /**
   * 手机号验证
   */
  public static boolean isMobile(String str) {
    Pattern p = null;
    Matcher m = null;
    boolean b = false;
    p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
    m = p.matcher(str);
    b = m.matches();
    return b;
  }

  /**
   * 判断手机浏览器
   * 
   * @param request
   * @return
   */
  public static boolean isMoblieBrowser(HttpServletRequest request) {
    boolean isMoblie = false;
    String[] mobileAgents = { "iphone", "android", "phone", "mobile", "wap", "netfront", "java", "opera mobi", "opera mini", "ucweb", "windows ce",
        "symbian", "series", "webos", "sony", "blackberry", "dopod", "nokia", "samsung", "palmsource", "xda", "pieplus", "meizu", "midp", "cldc",
        "motorola", "foma", "docomo", "up.browser", "up.link", "blazer", "helio", "hosin", "huawei", "novarra", "coolpad", "webos", "techfaith",
        "palmsource", "alcatel", "amoi", "ktouch", "nexian", "ericsson", "philips", "sagem", "wellcom", "bunjalloo", "maui", "smartphone",
        "iemobile", "spice", "bird", "zte-", "longcos", "pantech", "gionee", "portalmmm", "jig browser", "hiptop", "benq", "haier", "^lct",
        "320x320", "240x320", "176x220", "w3c ", "acs-", "alav", "alca", "amoi", "audi", "avan", "benq", "bird", "blac", "blaz", "brew", "cell",
        "cldc", "cmd-", "dang", "doco", "eric", "hipt", "inno", "ipaq", "java", "jigs", "kddi", "keji", "leno", "lg-c", "lg-d", "lg-g", "lge-",
        "maui", "maxo", "midp", "mits", "mmef", "mobi", "mot-", "moto", "mwbp", "nec-", "newt", "noki", "oper", "palm", "pana", "pant", "phil",
        "play", "port", "prox", "qwap", "sage", "sams", "sany", "sch-", "sec-", "send", "seri", "sgh-", "shar", "sie-", "siem", "smal", "smar",
        "sony", "sph-", "symb", "t-mo", "teli", "tim-", "tosh", "tsm-", "upg1", "upsi", "vk-v", "voda", "wap-", "wapa", "wapi", "wapp", "wapr",
        "webc", "winw", "winw", "xda", "xda-", "Googlebot-Mobile" };
    if (request.getHeader("User-Agent") != null) {
      for (String mobileAgent : mobileAgents) {
        if (request.getHeader("User-Agent").toLowerCase().indexOf(mobileAgent) >= 0) {
          if (mobileAgent.equals("tosh")) {
            if (request.getHeader("User-Agent").toLowerCase().indexOf("macintosh") == -1) {
              isMoblie = true;
              break;
            }
          } else {
            isMoblie = true;
            break;
          }
        }
      }
    }
    return isMoblie;
  }

  /**
   * 生成随机数
   * 
   * @param num1
   * @param num2
   * @return
   */
  public static int createRandom(int num1, int num2) {
    if (num1 > num2)
      return -1;
    Random rd = new Random();
    return num1 + rd.nextInt(num2 - num1 + 1);
  }

  /**
   * 验证时间字符串格式是否正确
   * 
   * @param str
   * @return
   */
  public static boolean isValidDate(String str, String formatStr) {
    if (isEmpty(formatStr))
      formatStr = "yyyyMMddHHmmss";
    SimpleDateFormat format = new SimpleDateFormat(formatStr);
    try {
      format.setLenient(true);
      format.parse(str);
      return true;
    } catch (ParseException e) {
      // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
      return false;
    }
  }

}
